/*
 * @Date: 2020-02-06 18:55:03
 * @名称: 分类 - 漫画列表 - 漫画信息 - 下载 - 内容 - 列表
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-23 00:10:24
 * @FilePath: /bica_acg/lib/Pages/ComicsInfoDownload/Widget/ComicsInfoDownloadComicsInfoDownloadBody/Widget/ComicsInfoDownloadComicsInfoDownloadBodyList.dart
 */
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pica_acg/DataBaseFunction.dart';
import 'package:pica_acg/GlobalKey.dart';
import 'package:pica_acg/GlobalVarlable.dart';
import 'package:pica_acg/Pages/ComicsInfoDownload/Widget/ComicsInfoDownloadComicsInfoDownloadBody/Widget/ComicsInfoDownloadComicsInfoDownloadBodyListDownloadProgress.dart';
import 'package:pica_acg/tools/extends/Json/ComicsInfo/all_chapter_list.dart';
import 'package:toast/toast.dart';

class ComicsInfoDownloadComicsInfoDownloadBodyList extends StatefulWidget {
  ComicsInfoDownloadComicsInfoDownloadBodyList({
    Key key,
    this.allChapter,
    this.comicsId,
    this.title,
  }) : super(key: key);
  final List<Docs> allChapter;
  final String comicsId;
  final String title;
  @override
  ComicsInfoDownloadComicsInfoDownloadBodyListState createState() =>
      ComicsInfoDownloadComicsInfoDownloadBodyListState();
}

var selectNumber = 0; //已选择数量
var downloadedLoading = 0; //下载中
var successNumber = 0; //已下载完成的数量
Map<String, dynamic> downloadList = Map();
var $downloadList;
Map $downloadListList = Map();

class ComicsInfoDownloadComicsInfoDownloadBodyListState
    extends State<ComicsInfoDownloadComicsInfoDownloadBodyList> {
  @override
  void initState() {
    super.initState();

    Future.delayed(Duration(seconds: 2), () {
      dataBaseSelect(
        "BookDownloadChapterList",
        'BookId = ? and Download = 0 and Success = 0',
        [widget.comicsId],
      ).then((info) {
        selectNumber = info.length;
        buttonKey.currentState
            .updateState(selectNumber > 0, bookId: widget.comicsId);
        refreshKey.currentState.updateDownloadValue(haveChosen: selectNumber);
      });
      dataBaseSelect(
        "BookDownloadChapterList",
        'BookId = ? and Download = 1 and Success = 0',
        [widget.comicsId],
      ).then((info) {
        downloadedLoading = info.length;
        refreshKey.currentState
            .updateDownloadValue(downloadedLoading: downloadedLoading);
      });
      dataBaseSelect(
        "BookDownloadChapterList",
        'BookId = ? and Download = 1 and Success = 1',
        [widget.comicsId],
      ).then((info) {
        successNumber = info.length;
        refreshKey.currentState.updateDownloadValue(downloaded: successNumber);
      });

      this.setState(() {});
    });
  }

  Widget build(BuildContext context) {
    dataBaseSelect(
      "BookDownloadChapterList",
      'BookId = ? ',
      [widget.comicsId],
    ).then((info) {
      $downloadList = info;
      for (var i = 0; i < $downloadList.length; i++) {
        $downloadListList[$downloadList[i]['ChapterId']] = $downloadList[i];
      }
    });

    return Container(
      height: ScreenUtil().setHeight(1030),
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(15), top: ScreenUtil().setHeight(12)),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: ListView(
          children: <Widget>[
            Wrap(
              spacing: 5, //主轴上子控件的间距
              runSpacing: 10, //交叉轴上子控件之间的间距
              children: List.generate(
                widget.allChapter.length,
                (index) {
                  var chapterId = widget.allChapter[index].id;
                  if (downList[widget.comicsId] == null) {
                    downList[widget.comicsId] = Map();
                  }
                  if (downList[widget.comicsId][chapterId] == null) {
                    downList[widget.comicsId][chapterId] = {
                      "Title": '${widget.allChapter[index].title}',
                      "Revised": false,
                      "Color": {
                        "Color": Color(0xffffffff),
                        "TextColor": Color(0xff000000),
                      },
                      "Extends": {
                        "Download": false,
                        "Success": false,
                        "Progress": 0.0,
                        "SetProgress": false,
                      }
                    };
                  }
                  if ($downloadListList[chapterId] == null) {
                    //没有加入下载列表
                  } else {
                    if ($downloadListList[chapterId]['Download'] == 1 &&
                        $downloadListList[chapterId]['Success'] == 0) {
                      if (downList[widget.comicsId][chapterId]['Extends']
                              ["SetProgress"] ==
                          false) {
                        //在下载列表 但是没有下载完成
                        downList[widget.comicsId][chapterId] = {
                          "Title": '${widget.allChapter[index].title}',
                          "Revised": true,
                          "Color": {
                            'Color': Color(0xffff9a05),
                            'TextColor': Color(0xffffffff),
                          },
                          "Extends": {
                            "Download": true,
                            "Success": false,
                            "Progress": $downloadListList[chapterId]
                                ["Progress"],
                            "SetProgress": false,
                          }
                        };
                      }
                    } else if ($downloadListList[chapterId]['Download'] == 0 &&
                        $downloadListList[chapterId]['Success'] == 0 &&
                        downList[widget.comicsId][chapterId]["Revised"] ==
                            false) {
                      //添加到下载列表  并未开始的
                      downList[widget.comicsId][chapterId] = {
                        "Title": '${widget.allChapter[index].title}',
                        "Revised": true,
                        "Color": {
                          'Color': Color(0xffec97b6),
                          'TextColor': Color(0xffffffff),
                        },
                        "Extends": {
                          "Download": false,
                          "Success": false,
                          "Progress": 0.0,
                          "SetProgress": false,
                        }
                      };
                    } else if ($downloadListList[chapterId]['Download'] == 1 &&
                        $downloadListList[chapterId]['Success'] == 1 &&
                        downList[widget.comicsId][chapterId]["Revised"] ==
                            false) {
                      //添加到下载列表  并未开始的
                      downList[widget.comicsId][chapterId] = {
                        "Title": '${widget.allChapter[index].title}',
                        "Revised": true,
                        "Color": {
                          'Color': Color(0xff00a656),
                          'TextColor': Color(0xffffffff),
                        },
                        "Extends": {
                          "Download": true,
                          "Success": true,
                          "Progress": 1.0,
                          "SetProgress": false,
                        }
                      };
                    }
                  }
                  return SizedBox(
                    child: Stack(
                      alignment: const FractionalOffset(0.1, 1.0),
                      children: [
                        GestureDetector(
                          child: Container(
                            child: Container(
                              width: ScreenUtil().setWidth(120),
                              margin: EdgeInsets.only(
                                left: ScreenUtil().setWidth(24),
                                right: ScreenUtil().setWidth(24),
                                top: ScreenUtil().setHeight(24),
                                bottom: ScreenUtil().setHeight(24),
                              ),
                              child: Text(
                                // widget.allChapter[index].Title,
                                downList[widget.comicsId][chapterId]['Title'],
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(30),
                                  fontWeight: FontWeight.w700,
                                  color: downList[widget.comicsId][chapterId]
                                      ['Color']['TextColor'],
                                  shadows: [
                                    BoxShadow(
                                        color: Colors.grey,
                                        offset: Offset(0.2, 0.2))
                                  ],
                                ),
                              ),
                            ),
                            decoration: new BoxDecoration(
                              color: downList[widget.comicsId][chapterId]
                                  ['Color']['Color'],
                              // color: block,
                              border: new Border.all(
                                  color: Color(0xFFf0f0f0),
                                  width: 1.0), // 边色与边宽度
                              //        borderRadius: new BorderRadius.circular((20.0)), // 圆度
                            ),
                          ),
                          onTap: () async {
                            void addDownloadListFunction() {
                              //添加到下载列表
                              selectNumber++;
                              buttonKey.currentState.updateState(
                                  selectNumber != 0,
                                  bookId: widget.comicsId);

                              // [chapterId] = true;
                              this.setState(() {
                                downList[widget.comicsId][chapterId]
                                        ['Revised'] =
                                    !downList[widget.comicsId][chapterId]
                                        ['Revised'];
                                refreshKey.currentState.updateDownloadValue(
                                    haveChosen: selectNumber);
                              });
                            }

                            void deleteDownloadListFunction() {
                              //删除下载列表
                              selectNumber--;
                              buttonKey.currentState.updateState(
                                  selectNumber > 0,
                                  bookId: widget.comicsId);

                              // [chapterId] = true;
                              this.setState(() {
                                // downList[widget.comicsId][chapterId]['Revised'] = !downList[widget.comicsId][chapterId]['Revised'];
                                downList[widget.comicsId][chapterId]
                                    ['Revised'] = true;

                                refreshKey.currentState.updateDownloadValue(
                                    haveChosen: selectNumber);
                              });
                            }

                            if (downList[widget.comicsId][chapterId]["Extends"]
                                        ["Download"] ==
                                    true ||
                                downList[widget.comicsId][chapterId]["Extends"]
                                        ["Success"] ==
                                    true) {
                              /*    var sDocumentDir =
                                  (await getApplicationDocumentsDirectory());
                              Stream<FileSystemEntity> entityList = sDocumentDir
                                  .list(recursive: true, followLinks: false);
                              await for (FileSystemEntity entity
                                  in entityList) {
                                print(entity.path);
                              } */
                              // var dataSpace = (await getApplicationDocumentsDirectory()).path;
                              // var file = Directory(dataSpace);
                              // file.delete(recursive: true);
                              // return;
                              print('队列中或者 下载完成的无法操作');
                            } else {
                              var currentState = dataBaseSelect(
                                //!判断这条数据 是否添加过数据库
                                "BookDownloadChapterList",
                                'BookId = ? and ChapterId = ?',
                                [widget.comicsId, chapterId],
                              );
                              currentState.then(
                                //!判断这条数据 是否添加过数据库
                                (data) {
                                  if (data.length > 0) {
                                    downList[widget.comicsId][chapterId]
                                        ['Color'] = {
                                      'Color': Color(0xffffffff),
                                      'TextColor': Color(0xff000000),
                                    };
                                    dataBaseDelete("BookDownloadChapterList",
                                        'id=?', [data[0]['id']]);
                                    deleteDownloadListFunction(); //删除分卷数据
                                    // 查询分卷诗句 是否还有本漫画的章节
                                    dataBaseSelect("BookDownloadChapterList",
                                        'BookId = ?', [widget.comicsId]).then(
                                      (value) {
                                        if (value.length < 1) {
                                          //*判断下载分卷全部取消了 删除下载列表的漫画记录
                                          dataBaseDelete("DownloadList",
                                              'BookId = ?', [widget.comicsId]);
                                        }
                                      },
                                    );
                                  } else {
                                    downList[widget.comicsId][chapterId]
                                        ['Color'] = {
                                      'Color': Color(0xffec97b6),
                                      'TextColor': Color(0xffffffff),
                                    };

                                    addDownloadListFunction();
                                    //*先查询下载漫画列表 有没有添加过这个漫画 不是漫画分卷
                                    dataBaseSelect("DownloadList", 'BookId = ?',
                                        [widget.comicsId]).then((value) {
                                      if (value.length < 1) {
                                        //确认没有添加过这个漫画 则进行添加
                                        dataBaseInsert("DownloadList", {
                                          "BookId": "${widget.comicsId}",
                                          "Title": "${widget.title}",
                                          "NetWorkCoverUrl":
                                              $globalVarlableBookCover["Src"],
                                          "LocalCoverUrl":
                                              "/Cartoon/${widget.comicsId}/" +
                                                  $globalVarlableBookCover[
                                                      "SeverName"],
                                        });
                                        downLoadCover(
                                            "${widget.comicsId}",
                                            $globalVarlableBookCover["Src"],
                                            $globalVarlableBookCover[
                                                "SeverName"]);
                                      }
                                    });
                                    dataBaseInsert(
                                      "BookDownloadChapterList",
                                      {
                                        "BookId": "${widget.comicsId}",
                                        "ChapterId": "${chapterId}",
                                        "title":
                                            "${widget.allChapter[index].title}",
                                        "Download": false,
                                        "Success": false,
                                        "Progress": 0.0
                                      },
                                    );
                                  }
                                },
                              );
                            }
                            /* dataBaseDelete(
                            "BookDownloadChapterList", 'id!=10000', [' whereArgs']); */
                          },
                        ),
                        Visibility(
                          visible: (downList[widget.comicsId][chapterId]
                                      ['Extends']["Download"] ==
                                  (downList[widget.comicsId][chapterId]
                                          ['Extends']["Success"] ==
                                      false))
                              ? true
                              : false,
                          child: Container(
                            margin: EdgeInsets.only(
                              // top: ScreenUtil().setHeight(124),
                              left: ScreenUtil().setWidth(2),
                            ),
                            child:
                                ComicsInfoDownloadComicsInfoDownloadBodyListDownloadProgress(
                              progress: downList[widget.comicsId][chapterId]
                                  ['Extends']["Progress"],
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  startDownload(Function callBack) {
    Toast.show(
      "已经开始下载",
      context,
      duration: Toast.LENGTH_LONG,
      gravity: Toast.BOTTOM,
    );
    dataBaseUpdate(
      "BookDownloadChapterList",
      {"Download": true, "Success": false, "Progress": 0.0},
      'BookId=? and Download = ?',
      [widget.comicsId, false],
    );
    /*  dataBaseDelete(
      "BookDownloadChapterList",
      'BookId != 1 ',
      [widget.comicsId],
    ).then((info) {
      $downloadList = info;
      block = Map();
    }); */
    dataBaseSelect(
      "BookDownloadChapterList",
      'BookId = ? ',
      [widget.comicsId],
    ).then((info) {
      $downloadList = info;
      for (var i = 0; i < $downloadList.length; i++) {
        downList[widget.comicsId][info[i]["ChapterId"]] = {
          "Title": downList[widget.comicsId][info[i]["ChapterId"]]['Title'],
          "Revised": true,
          "Color": {
            'Color': Color(0xffff9a05),
            'TextColor': Color(0xffffffff),
          },
          "Extends": {
            "Download": true,
            "Success": false,
          }
        };
        $downloadListList[$downloadList[i]['ChapterId']] = $downloadList[i];

        dataBaseSelect(
          "BookDownloadChapterList",
          'BookId = ? and Download = 0 and Success = 0',
          [widget.comicsId],
        ).then((info) {
          selectNumber = info.length;
          buttonKey.currentState
              .updateState(selectNumber > 0, bookId: widget.comicsId);
          refreshKey.currentState.updateDownloadValue(haveChosen: selectNumber);
        });
        dataBaseSelect(
          "BookDownloadChapterList",
          'BookId = ? and Download = 1 and Success = 0',
          [widget.comicsId],
        ).then((info) {
          downloadedLoading = info.length;
          refreshKey.currentState
              .updateDownloadValue(downloadedLoading: downloadedLoading);
        });
        dataBaseSelect(
          "BookDownloadChapterList",
          'BookId = ? and Download = 1 and Success = 1',
          [widget.comicsId],
        ).then((info) {
          successNumber = info.length;
          refreshKey.currentState
              .updateDownloadValue(downloaded: successNumber);
        });

        setState(() {});
      }
    });
    callBack(true);
  }

  modifyBlockLocation() {
    setState(() {});
  }
}

downLoadCover(
  String bookId,
  String url,
  String saveName,
) async {
  Dio dio = Dio();
  //判断断目录是否存在 不存在就创建
  var file = Directory(dataSpace + "/Cartoon");
  bool exists = await file.exists();
  if (!exists) {
    await file.create();
    await Directory(dataSpace + "/Cartoon/$bookId").create();
  }
  file = Directory(dataSpace + "/Cartoon/$bookId");
  exists = await file.exists();

  if (!exists) {
    await file.create();
  }

  try {
    await dio.download(url, dataSpace + "/Cartoon/$bookId/$saveName",
        onReceiveProgress: (int count, int total) {
      //进度
    });
  } on DioError catch (e) {
    print('downloadFile error---------$e');
  }
}
